#include "driver_myrtc.h"
#include <stdlib.h> 
#include <stdio.h>
#include <string.h>

static RTC_HandleTypeDef nettortc = {0};
static char *Netmonth[12] = {"January", "February", "March ", "April ", "May", "June ", "July ", "August ", "September ", "October ", "November ", "December "};


void  RTC_Timer_Init(void)
{
     __HAL_RCC_PWR_CLK_ENABLE();
     __HAL_RCC_BKP_CLK_ENABLE();
    HAL_PWR_EnableBkUpAccess();
    
    nettortc.Instance = RTC; 
    nettortc.Init.AsynchPrediv = 32767;    //1HZ
    nettortc.Init.OutPut = RTC_OUTPUTSOURCE_NONE;
    HAL_RTC_Init(&nettortc);  
}


void HAL_RTC_MspInit(RTC_HandleTypeDef *nettortc)
{
    if(nettortc->Instance == RTC)
    {
        RCC_OscInitTypeDef  RCC_OscInitStruct = {0};
        RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
        RCC_OscInitStruct.LSEState = RCC_LSE_ON;
        RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
        HAL_RCC_OscConfig(&RCC_OscInitStruct);
        
        RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
        PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC;
        PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSE; 
        HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);     
    }
}


void RTC_Set_Time(pNetTime RealTime)
{  
//    printf("%s:%s:%s %s/%s\r\n", RealTime->hour, RealTime->min, RealTime->sec, RealTime->month, RealTime->day);
    RTC_DateTypeDef sDate = {0};
    RTC_TimeTypeDef sTime = {0};
    int i = 0;
    for(i=0;i<12;i++)
    {
        if(strstr(Netmonth[i], RealTime->month) != NULL)
        {  
            break;
        }
    }
//    printf("%s:%s:%d:i= %d\r\n", __FILE__, __FUNCTION__, __LINE__, i);
    
    sDate.Year = atoi(RealTime->year) - 2000;
    sDate.Month = i + 1;
    sDate.Date = atoi(RealTime->day);
    HAL_RTC_SetDate(&nettortc, &sDate, RTC_FORMAT_BIN);
    
    sTime.Hours = atoi(RealTime->hour);
    sTime.Minutes = atoi(RealTime->min);
    sTime.Seconds = atoi(RealTime->sec);
    HAL_RTC_SetTime(&nettortc, &sTime, RTC_FORMAT_BIN);
    
    printf("%02d:%02d:%02d %02d/%02d\r\n", sTime.Hours, sTime.Minutes, sTime.Seconds, sDate.Month, sDate.Date);
}


void RTC_Get_Time(void)
{   
    char timeBuf[32] = {0};
    
    RTC_TimeTypeDef sTime = {0};
    HAL_RTC_GetTime(&nettortc, &sTime, RTC_FORMAT_BIN);
    RTC_DateTypeDef sDate = {0};
    HAL_RTC_GetDate(&nettortc, &sDate, RTC_FORMAT_BIN);
    
//    printf("%02d:%02d:%02d %02d/%02d\r\n", sTime.Hours, sTime.Minutes, sTime.Seconds, sDate.Month, sDate.Date);
    sprintf(timeBuf, "%02d:%02d:%02d %02d/%02d", sTime.Hours, sTime.Minutes, sTime.Seconds, sDate.Month, sDate.Date);
    oled->Display(oled, 6, 0, timeBuf);
    
}

